# -*- coding: utf-8 -*-
'''
程序入口
@author: lowzoom
'''
import PyQt4.QtCore as qtc
import PyQt4.QtGui as qt
import PyQt4.QtNetwork as qtn
import cfg
import logging
import os
import subprocess
import sys
import win32_util

# 程序信息
__author__ = 'lowZoom'
__version__ = '2.1'

# 程序所在目录
base_path = os.path.dirname(sys.argv[0])

def init_logging():
	'''
	初始化日志参数
	'''
	# 日志输出格式
	logging_formats = {
		'normal':'%(message)s |<%(asctime)s><%(levelname)s><%(pathname)s:%(lineno)d>|', # 普通输出格式
		'clickable':'%(message)s |<%(asctime)s><%(levelname)s>|\n  File "%(pathname)s", line %(lineno)d' # 可以点击链接到日志输出处
	}

	logging.basicConfig(
		level=logging.DEBUG,
		format=logging_formats['normal'],
		datefmt='%H:%M')

def single_instance(func):
	'''
	只允许一个实例
	@param func:
	'''
	def wrapper_func(*args):

		def send_hwnd():
			'''
			向重复的实例发送已运行实例的窗口ID
			'''
			hwnd = int(main_window.winId())
			sk = localServer.nextPendingConnection()
			sk.writeData(str(hwnd))
			sk.flush()

		socket = qtn.QLocalSocket()
		socket.connectToServer(app.applicationName())

		# 连接上表示已有运行的实例
		if socket.waitForConnected(500) \
		 and socket.waitForReadyRead(500):
			hwnd = int(socket.readAll())
			win32_util.activate_window(hwnd)
			app.exit(1)
			return

		# 没有实例运行，创建服务器		 
		localServer = qtn.QLocalServer()
		qtc.QObject.connect(localServer, qtc.SIGNAL('newConnection()'), send_hwnd)
		localServer.listen(app.applicationName())

		try:
			return func(*args)
		finally:
			localServer.close()

	return wrapper_func

@single_instance
def run():
	global main_window

	init_logging()
	cfg.load()

	main_window = MainWindow()
	main_window.show()

	sys.exit(app.exec_())

if __name__ == "__main__":
	subprocess.call('pyuic4 ui/_boot_dialog.ui > ui/_boot_dialog.py'.split(), shell=True)
	subprocess.call('pyrcc4 -o ui/_fifakey_rc.py ui/_fifakey.qrc'.split(), shell=True)
	subprocess.call('pyuic4 ui/_main_window.ui > ui/_main_window.py'.split(), shell=True)
	from ui.main_window import MainWindow

	app = qt.QApplication(sys.argv)
	app.setApplicationName('FIFA 12 Button Config')

	run()
